import React, {useEffect, useState} from 'react'
import {
	Form,
	Row,
	Col,
	Input,
	Select,
	DatePicker as TDatePicker,
	Cascader,
	TreeSelect,
} from 'antd'
import moment from 'moment'
import 'moment/locale/zh-cn'
import {connect, useDispatch} from 'umi'
import Styles from './index.less'
import {leaseTerm, subsidyType} from '../constant'
import {FormSelect} from '@/components/SearchForm/SearchFormItem'
import {getOrderType} from '@/service/marketing/commodity'
import Modal from './Modal/index'
import {getDict} from '@/service/common/dict'

moment.locale('zh-cn')

interface BasicsType {
	pageType: any
	routerQuery: any
	basicsForm: any
	code: any
	expire: boolean
	driverRewardRules: any
	callBack: any
	user: any
	setChannelTypename: any
}
const DatePicker: any = TDatePicker
const changeList: any = [
	{
		name: '主体名称',
		key: 'subjectId',
		msg: '关联商品方案数据尚未保存，确定还要改变主体名称吗？',
	},
	{
		name: '所属公司',
		key: 'orgId',
		msg: '关联商品方案数据尚未保存，确定还要改变所属公司吗？',
	},
	{
		name: '城市名称',
		key: 'cityId',
		msg: '关联商品方案数据尚未保存，确定还要改变城市名称吗？',
	},
	{
		name: '品牌/车系/车型',
		key: 'rewardModelList',
		msg: '关联商品方案数据尚未保存，确定还要改变品牌/车系/车型吗？',
	},
	{
		name: '租期',
		key: 'leaseTerm',
		msg: '关联商品方案数据尚未保存，确定还要改变租期吗？',
	},
	{
		name: '租赁类型',
		key: 'leaseType',
		msg: '关联商品方案数据尚未保存，确定还要改变租赁类型吗？',
	},
	{
		name: '开始时间',
		key: 'startTime',
		msg: '关联商品方案数据尚未保存，确定还要改变开始时间吗？',
	},
	{
		name: '结束时间',
		key: 'endTime',
		msg: '关联商品方案数据尚未保存，确定还要改变结束时间吗？',
	},
]
function Basics({
	pageType,
	routerQuery,
	basicsForm,
	code,
	expire,
	driverRewardRules,
	callBack,
	user,
	setChannelTypename,
}: BasicsType) {
	const [isExpire, setIsExpire] = useState<boolean>(false)
	const [orderType, setOrderType] = useState<any>([])
	const dispatch = useDispatch()
	const {permissionID} = user
	// 操作提示
	const [isModalOpen, setIsModalOpen] = useState<any>(false)
	// 复制初始值

	const [selectItem, setSelectItem] = useState<any>()
	const [dictData, setDictData] = useState<any>({}) // 字典数据

	// 价格数据
	const onSubmitCostitemList = () => {
		const data = basicsForm.getFieldsValue()
		if (selectItem.key === 'subjectId') {
			dispatch({
				type: 'driverRewardRules/getCompany',
				payload: {
					merchantId: data.subjectId,
				},
			})
			basicsForm.setFieldsValue({
				orgId: null,
				cityId: null,
			})
		}
		if (selectItem.key === 'orgId') {
			dispatch({
				type: 'driverRewardRules/getAllPermission',
				payload: {
					permission: permissionID,
					orgId: data?.orgId,
				},
			})
			basicsForm.setFieldsValue({
				cityId: null,
			})
		}
		dispatch({
			type: 'driverRewardRules/updateState',
			payload: {
				outTableList: [],
			},
		})
		setIsModalOpen(false)
	}
	// 取消变化
	const onCancelCostitemList = () => {
		basicsForm.setFieldsValue(driverRewardRules.basicCopy)
		setIsModalOpen(false)
	}
	// 表单数据关联变化
	const onChangeList = (key: string) => {
		const item = changeList?.filter(
			(opt: {key: string}) => opt?.key === key,
		)[0]
		setSelectItem(() => item)
		setIsModalOpen(true)
	}
	/**
	 *
	 * @param value 主体名称变化
	 * @param option
	 */
	const onSubjectNameChange = (value: string) => {
		if (driverRewardRules?.outTableList.length) {
			onChangeList('subjectId')
		} else {
			dispatch({
				type: 'driverRewardRules/getCompany',
				payload: {
					merchantId: value,
				},
			})
			basicsForm.setFieldsValue({
				orgId: null,
				cityId: null,
			})
		}
	}
	useEffect(() => {
		getOrderType().then((res: any) => {
			if (res?.success) {
				setOrderType(() => res?.data)
			}
		})
		getDict(
			{
				dictKeys: ['Car_Channel_Type'],
			},
			(res: any) => {
				setDictData(res)
			},
		)
	}, [])

	// 所属公司变化
	const onOrgIdChange = (value: any) => {
		if (driverRewardRules?.outTableList.length) {
			onChangeList('orgId')
		} else {
			dispatch({
				type: 'driverRewardRules/getAllPermission',
				payload: {
					permission: permissionID,
					orgId: value,
				},
			})
			basicsForm.setFieldsValue({
				cityId: null,
			})
		}
	}

	// 城市变化
	const onCityChange = () => {
		if (driverRewardRules?.outTableList.length) {
			onChangeList('cityId')
		}
	}

	// 品牌/车系/车型变化
	const onRewardModelListChange = () => {
		// const data = basicsForm.getFieldsValue()
		if (driverRewardRules?.outTableList.length) {
			onChangeList('rewardModelList')
		}
	}

	// 租期变化
	const onLeaseTermChange = (value: any) => {
		if (driverRewardRules?.outTableList.length) {
			onChangeList('leaseTerm')
		}
		if (value.length) {
			dispatch({
				type: 'driverRewardRules/updateState',
				payload: {
					MAXTERM: Math.max(...value),
				},
			})
			callBack(true)
		} else {
			dispatch({
				type: 'driverRewardRules/updateState',
				payload: {
					MAXTERM: '',
				},
			})
			callBack(true)
		}
	}
	// 租赁类型变化
	const onLeaseTypeChange = () => {
		if (driverRewardRules?.outTableList.length) {
			onChangeList('leaseType')
		}
	}

	// 开始时间变化
	const onStartTimeChange = () => {
		if (driverRewardRules?.outTableList.length) {
			onChangeList('startTime')
		}
	}

	// 开始时间变化
	const onEndTimeChange = () => {
		if (driverRewardRules?.outTableList.length) {
			onChangeList('endTime')
		}
	}

	const onValuesChange = () => {
		const data = basicsForm.getFieldsValue()
		// 关联商品查询数据
		dispatch({
			type: 'driverRewardRules/updateState',
			payload: {
				basic: data,
			},
		})
	}

	// 设置开始日期不能选择的时间
	const disabledFinishTimeDate = (startValue: any) => {
		const endTime = basicsForm.getFieldValue('endTime')
		if (!startValue || !endTime) {
			return false
		}
		return startValue.valueOf() > endTime.valueOf()
	}

	// 设置结束不能选择的时间
	const disabledStartTimeDate = (endValue: any) => {
		const startTime = basicsForm.getFieldValue('startTime')
		if (!endValue || !startTime) {
			return false
		}
		return endValue.valueOf() <= startTime.valueOf()
	}
	const onChannelTypeChange = (key: any, value: any) => {
		setChannelTypename(value?.dictValue)
	}
	return (
		<div className={Styles.basics}>
			<div className={Styles.titleBox}>基础信息</div>
			<div className={Styles.formBox}>
				<Form
					layout="horizontal"
					labelCol={{flex: '140px'}}
					labelAlign="right"
					labelWrap
					autoComplete="off"
					name="PersonalInformationFom"
					form={basicsForm}
					onValuesChange={onValuesChange}
					disabled={
						routerQuery.pageType === 'detail' ||
						routerQuery.pageType === 'process'
					}>
					<Row>
						<Col sm={{span: 24}} md={{span: 12}} lg={{span: 8}}>
							<Form.Item
								label="奖励名称"
								name="rewardName"
								rules={[{required: true}]}>
								<Input
									placeholder="请输入"
									disabled={
										pageType === 'detail' ||
										pageType === 'process'
									}
								/>
							</Form.Item>
						</Col>
						<Col sm={{span: 24}} md={{span: 12}} lg={{span: 8}}>
							<Form.Item
								label="主体名称"
								name="subjectId"
								rules={[{required: true}]}>
								<Select
									placeholder="请选择"
									fieldNames={{
										value: 'id',
										label: 'name',
									}}
									showSearch
									optionFilterProp="name"
									disabled={
										routerQuery.type === '1' ||
										pageType === 'detail' ||
										pageType === 'process'
									}
									onChange={onSubjectNameChange}
									options={code?.MainCompany}
								/>
							</Form.Item>
						</Col>
						<Col span={24} />
						<Col sm={{span: 24}} md={{span: 12}} lg={{span: 8}}>
							<Form.Item
								label="所属公司"
								name="orgId"
								rules={[{required: true}]}>
								<TreeSelect
									dropdownStyle={{
										maxHeight: 400,
										overflow: 'auto',
									}}
									showSearch
									treeNodeFilterProp="name"
									placeholder="请选择"
									allowClear
									disabled={
										routerQuery.type === '1' ||
										pageType === 'detail' ||
										pageType === 'process'
									}
									treeDefaultExpandAll
									fieldNames={{
										label: 'name',
										value: 'id',
									}}
									onChange={onOrgIdChange}
									treeDataSimpleMode
									treeData={code?.companyData}
								/>
							</Form.Item>
						</Col>
						<Col sm={{span: 24}} md={{span: 12}} lg={{span: 8}}>
							<Form.Item
								label="城市名称"
								name="cityId"
								rules={[{required: true}]}>
								<Cascader
									fieldNames={{
										// cityName
										label: 'name',
										value: 'id',
										children: 'cityInfoList',
									}}
									disabled={
										routerQuery.type === '1' ||
										pageType === 'detail' ||
										pageType === 'process'
									}
									options={code?.cityData}
									onChange={onCityChange}
									placeholder="请选择"
								/>
							</Form.Item>
						</Col>
						<Col span={24} />
						<Col sm={{span: 24}} md={{span: 12}} lg={{span: 8}}>
							<FormSelect
								name="rewardModelList"
								label="品牌/车系/车型"
								placeholder="请选择品牌/车系/车型"
								showSearch
								optionFilterProp="fullName"
								keys="id"
								mode="multiple"
								title="fullName"
								disabled={
									routerQuery.type === '1' ||
									pageType === 'detail' ||
									pageType === 'process'
								}
								onChange={onRewardModelListChange}
								rules={[{required: true}]}
								items={code?.carTypeList}
							/>
						</Col>
						<Col sm={{span: 24}} md={{span: 12}} lg={{span: 8}}>
							<Form.Item
								label="租期"
								name="leaseTerm"
								rules={[{required: true}]}>
								<Select
									placeholder="请选择"
									fieldNames={{
										value: 'value',
										label: 'label',
									}}
									showSearch
									optionFilterProp="label"
									mode="multiple"
									disabled={
										routerQuery.type === '1' ||
										pageType === 'detail' ||
										pageType === 'process'
									}
									options={[...leaseTerm]}
									onChange={onLeaseTermChange}
								/>
							</Form.Item>
						</Col>
						<Col span={24} />
						<Col sm={{span: 24}} md={{span: 12}} lg={{span: 8}}>
							<Form.Item
								label="租赁类型"
								name="leaseType"
								rules={[{required: true}]}>
								<Select
									placeholder="请选择"
									fieldNames={{
										value: 'code',
										label: 'name',
									}}
									disabled={
										routerQuery.type === '1' ||
										pageType === 'detail' ||
										pageType === 'process'
									}
									onChange={onLeaseTypeChange}
									options={[...orderType]}
								/>
							</Form.Item>
						</Col>
						<Col sm={{span: 24}} md={{span: 12}} lg={{span: 8}}>
							<Form.Item
								label="渠道类型"
								name="channelType"
								rules={[{required: true}]}>
								<Select
									placeholder="请选择"
									fieldNames={{
										value: 'dictKey',
										label: 'dictValue',
									}}
									onChange={onChannelTypeChange}
									options={dictData?.Car_Channel_Type}
								/>
							</Form.Item>
						</Col>
						<Col span={24} />
						<Col sm={{span: 24}} md={{span: 12}} lg={{span: 8}}>
							<Form.Item
								label="补贴订单类型"
								name="subsidyType"
								rules={[{required: true}]}>
								<Select
									placeholder="请选择"
									fieldNames={{
										value: 'value',
										label: 'label',
									}}
									disabled={
										pageType === 'detail' ||
										pageType === 'process'
									}
									mode="multiple"
									options={[...subsidyType]}
									onChange={(value) =>
										setIsExpire(value.includes(3))
									}
								/>
							</Form.Item>
						</Col>
						<Col sm={{span: 24}} md={{span: 12}} lg={{span: 16}}>
							{isExpire || expire ? (
								<div className={Styles.inputBox}>
									<Form.Item
										label="提前续规则到期前"
										name="renewalDays"
										rules={[
											{required: isExpire || expire},
										]}>
										<Input
											placeholder="请输入"
											disabled={
												pageType === 'detail' ||
												pageType === 'process'
											}
										/>
									</Form.Item>
									<div className={Styles.text}>天前续费</div>
								</div>
							) : (
								<></>
							)}
						</Col>
						<Col span={24} />
						<Col sm={{span: 24}} md={{span: 12}} lg={{span: 8}}>
							<Form.Item
								label="开始时间"
								name="startTime"
								rules={[{required: true}]}>
								<DatePicker
									showTime={{format: 'HH'}}
									format="YYYY-MM-DD HH:00"
									disabled={
										routerQuery.type === '1' ||
										pageType === 'detail' ||
										pageType === 'process'
									}
									disabledDate={disabledFinishTimeDate}
									onChange={onStartTimeChange}
								/>
							</Form.Item>
						</Col>
						<Col sm={{span: 24}} md={{span: 12}} lg={{span: 8}}>
							<Form.Item
								label="结束时间"
								name="endTime"
								rules={[{required: true}]}>
								<DatePicker
									showTime={{format: 'HH'}}
									format="YYYY-MM-DD HH:00"
									disabled={
										routerQuery.type === '1' ||
										pageType === 'detail' ||
										pageType === 'process'
									}
									disabledDate={disabledStartTimeDate}
									onChange={onEndTimeChange}
								/>
							</Form.Item>
						</Col>
					</Row>
					<Row>
						<Col sm={{span: 24}} md={{span: 12}} lg={{span: 16}}>
							<Form.Item label="备注" name="remarks">
								<Input.TextArea
									disabled={
										pageType === 'detail' ||
										pageType === 'process'
									}
									placeholder="请填写处理意见,最多不超过200个字"
									rows={4}
								/>
							</Form.Item>
						</Col>
					</Row>
				</Form>
			</div>
			<Modal
				text={`${selectItem?.msg}`}
				onSubmit={onSubmitCostitemList}
				onCancel={onCancelCostitemList}
				isModalOpen={isModalOpen}
				setIsModalOpen={setIsModalOpen}
			/>
		</div>
	)
}

export default connect(({driverRewardRules, user}: any) => ({
	driverRewardRules,
	user,
}))(Basics)
